const cartModel = require('../models/cartModel');
const { sendSuccess, sendError } = require('../utils/response');

module.exports = {
  // 获取购物车
  async getCart(req, res) {
    try {
      const { id: userId } = req.user;
      const cartItems = await cartModel.getCartByUserId(userId);
      sendSuccess(res, cartItems);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 添加商品到购物车
  async addToCart(req, res) {
    try {
      const { id: userId } = req.user;
      const { product_id, quantity } = req.body;
      
      if (!product_id) {
        return sendError(res, '缺少商品ID', 400);
      }
      
      await cartModel.addToCart(userId, product_id, quantity || 1);
      const cartItems = await cartModel.getCartByUserId(userId);
      sendSuccess(res, cartItems, '商品已添加到购物车');
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 更新购物车商品数量
  async updateCartItem(req, res) {
    try {
      const { id: userId } = req.user;
      const { id } = req.params;
      const { quantity } = req.body;
      
      if (!quantity || quantity < 1) {
        return sendError(res, '数量必须大于0', 400);
      }
      
      await cartModel.updateCartItem(userId, id, quantity);
      const cartItems = await cartModel.getCartByUserId(userId);
      sendSuccess(res, cartItems, '购物车已更新');
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 从购物车移除商品
  async removeFromCart(req, res) {
    try {
      const { id: userId } = req.user;
      const { id } = req.params;
      
      await cartModel.removeFromCart(userId, id);
      const cartItems = await cartModel.getCartByUserId(userId);
      sendSuccess(res, cartItems, '商品已从购物车移除');
    } catch (err) {
      sendError(res, err.message);
    }
  }
};